{% extends 'base/base.html' %}

{% block title %}Webhook URL列表 - 完整展示{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1>
                    <i class="fa fa-link" aria-hidden="true"></i> Webhook URL完整列表
                </h1>
                <div>
                    <button class="btn btn-outline-secondary" onclick="exportToJSON()">
                        <i class="fa fa-download"></i> 导出JSON
                    </button>
                    <button class="btn btn-outline-primary" onclick="copyAllURLs()">
                        <i class="fa fa-copy"></i> 复制所有URL
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 加载状态 -->
    <div id="loadingSpinner" class="text-center py-5">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-3 text-muted">正在加载webhook数据...</p>
    </div>

    <!-- 错误提示 -->
    <div id="errorAlert" class="alert alert-danger" style="display: none;">
        <i class="fa fa-exclamation-triangle"></i>
        <strong>加载失败：</strong>
        <span id="errorMessage"></span>
        <button class="btn btn-sm btn-outline-danger float-end" onclick="loadWebhooks()">重试</button>
    </div>

    <!-- 主要内容 -->
    <div id="mainContent" style="display: none;">
        <!-- 统计信息 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 class="mb-0" id="totalCount">0</h4>
                                <p class="mb-0">总Webhooks</p>
                            </div>
                            <div class="align-self-center">
                                <i class="fa fa-plug fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 class="mb-0" id="activeCount">0</h4>
                                <p class="mb-0">已激活</p>
                            </div>
                            <div class="align-self-center">
                                <i class="fa fa-check-circle fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 class="mb-0" id="projectCount">0</h4>
                                <p class="mb-0">项目数</p>
                            </div>
                            <div class="align-self-center">
                                <i class="fa fa-folder fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 class="mb-0" id="channelCount">0</h4>
                                <p class="mb-0">渠道类型</p>
                            </div>
                            <div class="align-self-center">
                                <i class="fa fa-broadcast-tower fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <div class="row mb-3">
            <div class="col-md-6">
                <input type="text" class="form-control" id="searchInput" placeholder="搜索项目名称或Webhook名称...">
            </div>
            <div class="col-md-3">
                <select class="form-select" id="statusFilter">
                    <option value="">所有状态</option>
                    <option value="active">已激活</option>
                    <option value="inactive">已禁用</option>
                </select>
            </div>
            <div class="col-md-3">
                <select class="form-select" id="projectFilter">
                    <option value="">所有项目</option>
                </select>
            </div>
        </div>

        <!-- Webhook列表 -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Webhook详细信息</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover" id="webhookTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>项目</th>
                                        <th>Webhook名称</th>
                                        <th>完整URL</th>
                                        <th>渠道</th>
                                        <th>事件</th>
                                        <th>状态</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="webhookTableBody">
                                    <!-- 数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- URL格式说明 -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fa fa-info-circle"></i> Webhook URL格式说明
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6><i class="fa fa-star text-primary"></i> 标准格式（推荐）：</h6>
                            <code class="d-block p-2 bg-light">http://{{ request.get_host }}/webhooks/&lt;项目ID&gt;/&lt;Webhook ID&gt;/receive/</code>
                            <small class="text-muted">使用项目ID，适用于所有场景</small>
                        </div>
                        <div class="col-md-6">
                            <h6><i class="fa fa-star text-success"></i> 替代格式：</h6>
                            <code class="d-block p-2 bg-light">http://{{ request.get_host }}/webhooks/&lt;项目Slug&gt;/&lt;Webhook ID&gt;/receive/</code>
                            <small class="text-muted">使用项目Slug，更易于记忆</small>
                        </div>
                    </div>
                    <hr>
                    <div class="alert alert-info">
                        <h6><i class="fa fa-lightbulb"></i> 使用说明：</h6>
                        <ul class="mb-0">
                            <li><strong>项目ID：</strong>项目的数字标识符，可在项目详情中查看</li>
                            <li><strong>Webhook ID：</strong>每个Webhook的唯一UUID标识符</li>
                            <li><strong>项目Slug：</strong>项目的URL友好名称</li>
                            <li><strong>重要：</strong>URL末尾必须包含 <code>/receive/</code> 才能正确接收webhook</li>
                            <li><strong>测试：</strong>可以使用POST方法测试webhook，支持JSON格式数据</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let webhookData = [];
let filteredData = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadWebhooks();
});

async function loadWebhooks() {
    const loadingSpinner = document.getElementById('loadingSpinner');
    const errorAlert = document.getElementById('errorAlert');
    const mainContent = document.getElementById('mainContent');
    
    loadingSpinner.style.display = 'block';
    errorAlert.style.display = 'none';
    mainContent.style.display = 'none';
    
    try {
        const response = await fetch('{% url "projects:api_webhooks" %}');
        if (!response.ok) {
            throw new Error(`HTTP错误! 状态: ${response.status}`);
        }
        
        const data = await response.json();
        webhookData = data.webhooks;
        filteredData = [...webhookData];
        
        loadingSpinner.style.display = 'none';
        mainContent.style.display = 'block';
        
        initPage();
    } catch (error) {
        loadingSpinner.style.display = 'none';
        errorAlert.style.display = 'block';
        document.getElementById('errorMessage').textContent = error.message;
        console.error('加载webhook数据失败:', error);
    }
}

function initPage() {
    updateStats();
    populateFilters();
    renderTable();
    setupEventListeners();
}

function updateStats() {
    document.getElementById('totalCount').textContent = webhookData.length;
    document.getElementById('activeCount').textContent = webhookData.filter(w => w.is_active).length;
    document.getElementById('projectCount').textContent = new Set(webhookData.map(w => w.project.name)).size;
    document.getElementById('channelCount').textContent = new Set(webhookData.map(w => w.channel)).size;
}

function populateFilters() {
    const projects = [...new Set(webhookData.map(w => w.project.name))].sort();
    const projectFilter = document.getElementById('projectFilter');
    
    // 清空现有选项（保留"所有项目"）
    projectFilter.innerHTML = '<option value="">所有项目</option>';
    
    projects.forEach(project => {
        const option = document.createElement('option');
        option.value = project;
        option.textContent = project;
        projectFilter.appendChild(option);
    });
}

function setupEventListeners() {
    document.getElementById('searchInput').addEventListener('input', filterData);
    document.getElementById('statusFilter').addEventListener('change', filterData);
    document.getElementById('projectFilter').addEventListener('change', filterData);
}

function filterData() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    const statusFilter = document.getElementById('statusFilter').value;
    const projectFilter = document.getElementById('projectFilter').value;
    
    filteredData = webhookData.filter(webhook => {
        const matchesSearch = webhook.name.toLowerCase().includes(searchTerm) || 
                             webhook.project.name.toLowerCase().includes(searchTerm) ||
                             webhook.description.toLowerCase().includes(searchTerm);
        const matchesStatus = !statusFilter || 
                             (statusFilter === 'active' && webhook.is_active) ||
                             (statusFilter === 'inactive' && !webhook.is_active);
        const matchesProject = !projectFilter || webhook.project.name === projectFilter;
        
        return matchesSearch && matchesStatus && matchesProject;
    });
    
    renderTable();
}

function renderTable() {
    const tbody = document.getElementById('webhookTableBody');
    tbody.innerHTML = '';
    
    if (filteredData.length === 0) {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td colspan="8" class="text-center py-4">
                <i class="fa fa-search fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">没有找到匹配的webhook</h5>
                <p class="text-muted">请尝试调整搜索条件或筛选器</p>
            </td>
        `;
        tbody.appendChild(row);
        return;
    }
    
    filteredData.forEach(webhook => {
        const row = document.createElement('tr');
        const eventsDisplay = webhook.events.slice(0, 3).map(event => 
            `<span class="badge bg-light text-dark me-1">${event}</span>`
        ).join('');
        const moreEvents = webhook.events.length > 3 ? 
            `<small class="text-muted">+${webhook.events.length - 3}更多</small>` : '';
        
        row.innerHTML = `
            <td>
                <strong>${webhook.project.name}</strong>
                <br><small class="text-muted">ID: ${webhook.project.id}</small>
            </td>
            <td>
                <strong>${webhook.name}</strong>
                ${webhook.description ? `<br><small class="text-muted">${webhook.description}</small>` : ''}
                <br><small class="text-muted">${webhook.id.substring(0, 8)}...</small>
            </td>
            <td>
                <div class="webhook-url-display">
                    <code class="d-block p-2 bg-light" title="${webhook.url}">
                        ${webhook.url}
                    </code>
                    <div class="mt-1">
                        <button class="btn btn-sm btn-outline-secondary" onclick="copyURL('${webhook.url}')">
                            <i class="fa fa-copy"></i> 复制
                        </button>
                        <button class="btn btn-sm btn-outline-primary" onclick="copyURL('${webhook.alt_url}')">
                            <i class="fa fa-copy"></i> 复制Slug
                        </button>
                    </div>
                </div>
            </td>
            <td>
                <span class="badge bg-secondary">${webhook.channel}</span>
            </td>
            <td>
                <div class="webhook-events">
                    ${eventsDisplay}${moreEvents}
                </div>
            </td>
            <td>
                <span class="badge ${webhook.is_active ? 'bg-success' : 'bg-danger'}">
                    ${webhook.status}
                </span>
            </td>
            <td>${webhook.created_at}</td>
            <td>
                <div class="btn-group">
                    <button class="btn btn-sm btn-outline-secondary" onclick="copyURL('${webhook.url}')" title="复制URL">
                        <i class="fa fa-copy"></i>
                    </button>
                    <a href="${webhook.url}" class="btn btn-sm btn-outline-primary" target="_blank" title="测试">
                        <i class="fa fa-external-link"></i>
                    </a>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

function copyURL(url) {
    navigator.clipboard.writeText(url).then(() => {
        showToast('URL已复制到剪贴板', 'success');
    }).catch(err => {
        console.error('复制失败:', err);
        showToast('复制失败，请手动选择并复制URL', 'error');
    });
}

function copyAllURLs() {
    const urls = filteredData.map(w => w.url).join('\n');
    navigator.clipboard.writeText(urls).then(() => {
        showToast(`${filteredData.length}个URL已复制`, 'success');
    }).catch(err => {
        console.error('复制失败:', err);
        showToast('复制失败，请重试', 'error');
    });
}

function exportToJSON() {
    const data = filteredData.map(w => ({
        name: w.name,
        description: w.description,
        project: w.project.name,
        url: w.url,
        alt_url: w.alt_url,
        channel: w.channel,
        events: w.events,
        is_active: w.is_active,
        created_at: w.created_at,
        last_triggered_at: w.last_triggered_at,
        trigger_count: w.trigger_count
    }));
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `webhooks_${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    showToast('JSON文件已下载', 'success');
}

function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type === 'error' ? 'danger' : type} position-fixed`;
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    toast.innerHTML = `
        <div class="d-flex align-items-center">
            <i class="fa fa-${type === 'success' ? 'check' : type === 'error' ? 'times' : 'info'}-circle me-2"></i>
            ${message}
            <button type="button" class="btn-close ms-auto" onclick="this.parentElement.parentElement.remove()"></button>
        </div>
    `;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        if (toast.parentElement) {
            document.body.removeChild(toast);
        }
    }, 3000);
}
</script>

<style>
.webhook-url-display {
    max-width: 400px;
}

.webhook-url-display code {
    font-size: 12px;
    word-break: break-all;
    white-space: pre-wrap;
}

.webhook-events {
    max-width: 200px;
}

@media (max-width: 768px) {
    .webhook-url-display {
        max-width: 100%;
    }
    
    .table-responsive table {
        font-size: 14px;
    }
}
</style>
{% endblock %}